/**
 * @author 徐楠
 * @date 2022/4/25 21:31
 * @version 1.0
 */

package com.xunan.likou;

import java.util.*;

public class SortByCharacterFrequency {
    public static void main(String[] args) {
        String s = "tree";
        String result = frequencySort(s);
        System.out.println(result);

    }

    public static String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        char[] chars = s.toCharArray();
        for (char aChar : chars) {
            map.put(aChar, map.getOrDefault(aChar, 0) + 1);
        }
        Set<Character> characters = map.keySet();
        System.out.println(characters.toString());
        List<Character> list = new ArrayList<>(characters);
        Collections.sort(list, new Comparator<Character>() {
            @Override
            public int compare(Character o1, Character o2) {
                return map.get(o2) - map.get(o1);
            }
        });
        StringBuffer stringBuffer = new StringBuffer();
        int size = list.size();
        for (int i = 0; i < size; i++) {
            char c = list.get(i);
            int frequency = map.get(c);
            for (int j = 0; j < frequency; j++) {
                stringBuffer.append(c);
            }
        }
        return stringBuffer.toString();

    }
}
